package com.zk.service;

import com.zk.mapper.BlogMapper;
import com.zk.mapper.DiscussMapper;
import com.zk.model.Blog;
import com.zk.model.Discuss;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private DiscussMapper discussMapper;

    @Override
    public void saveBlog(Blog blog) {
        blog.setCreateTime(new Date());
        blog.setCreateBy("ZK");
        blogMapper.createLambdaQuery().insertSelective(blog);
    }

    @Override
    public PageQuery<Blog> queryBlog(String keywords, Integer pageNo, Integer pageSize) {

        LambdaQuery<Blog> lambdaQuery = blogMapper.createLambdaQuery();
        if (!StringUtils.isEmpty(keywords)){
            lambdaQuery.andLike(Blog::getTitle, "%" + keywords + "%");
        }
        PageQuery<Blog> pageBlog = lambdaQuery.desc(Blog::getCreateTime).page(pageNo, pageSize);
        return pageBlog;
    }

    @Override
    public List<String> queryBlogGroupByMonth() {

        List<String> stringList = blogMapper.createLambdaQuery().groupBy(v -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            return sdf.format(v.getCreateTime());
        }).desc(Blog::getCreateTime).select().stream().map(v -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            return sdf.format(v.getCreateTime());
        }).collect(Collectors.toList());
        return stringList;
    }

    @Override
    public Blog queryOneBlog(Integer id) {
        Blog blog = blogMapper.createLambdaQuery().andEq(Blog::getId, id).single();
        return blog;
    }

    @Override
    public PageQuery<Discuss> queryDiscuss(Integer blogId, Integer pageNo, Integer pageSize) {
        PageQuery<Discuss> pageDiscuss = discussMapper.createLambdaQuery()
                .andEq(Discuss::getBlogId, blogId)
                .desc(Discuss::getCreateTime)
                .page(pageNo, pageSize);
        return pageDiscuss;
    }

    @Override
    public void saveDiscuss(Discuss discuss) {
        discuss.setCreateTime(new Date());
        discuss.setCreateBy("ZK");
        discussMapper.insertTemplate(discuss);
    }
}
